<?php

namespace App\Http\Controllers\Admin;

use Carbon\Carbon;
use App\Response\Response;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;                //引用http请求类

class QuestionController extends BaseController
{
    /**
     * @api {get} question 题目列表
     * @apiVersion 0.1.0
     * @apiName 题目列表
     * @apiGroup 题库
     * @apiParam {string} title   题目名称,非必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 1,
     * "title": "在爱情里你属于？",
     * "sort": 1,
     * "add_time": 1612322566,
     * "status 1显示2隐藏": 1,
     * "qa_answer": [
     * {
     * "id": 1,
     * "title": "A.不争不抢，随缘",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 2,
     * "title": "B.主动出击",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 3,
     * "title": "C.欲拒还迎",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 4,
     * "title": "D.遍地撒网",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * }
     * ]
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": "1",
     * "next": "http://www.na.com/question?page=2",
     * "total": 54
     * }
     * }
     * }
     */
    public function index(Request $request)
    {
        $where = [];
        $title = $request->input('title');
        if ($title) {
            $where[] = ['title', 'like', "%$title%"];
        }
        $perPage = $request->input('perPage', 15);
        $list = app('model_qa_question')->with([
            'qa_answer' => function ($query) {
                $query->orderBy('sort', 'asc')->orderBy('id', 'asc');
            },
        ])->where($where)->paginate($perPage);

        return Response::sendList($list);
    }

    /**
     * @api {post} question 添加修改题目
     * @apiVersion 0.1.0
     * @apiName 添加修改题目
     * @apiGroup 题库
     * @apiParam {numeric} id   题目id(如果不传id则添加,传id则修改),非必传
     * @apiParam {string} title   题目名称,必传
     * @apiParam {numeric} sort   排序,非必传,默认为0
     * @apiParam {string} answers  答案,非必传 [{"title":"肉","sort":"1"},{"title":"鱼","sort":"2"}]
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function update(Request $request)
    {
        $data = $request->only(['title', 'sort']);
        if (!isset($data['title']) || !$data['title']) {
            throw new BasicException(0, '题目名称不能为空');
        }
        $data['sort'] = $data['sort'] ?? 0;
        $id = intval($request->input('id', 0));
        $answers = $request->input('answers');
        $answers = json_decode($answers, true);
        $insert_data = [];
        foreach ($answers as $answer) {
            if (!isset($answer['title']) || !$answer['title']) {
                continue;
            }
            $insert_data[] = [
                'title'       => $answer['title'],
                'question_id' => $id,
                'sort'        => $answer['sort'] ?? 0,
                'add_time'    => Carbon::now()->timestamp,
            ];
        }

        DB::beginTransaction();
        try {
            if ($id > 0) {
                app('model_qa_question')->where('id', $id)->update($data);
                if (!empty($insert_data)) {
                    app('model_qa_answer')->where('question_id', $id)->delete();
                    app('model_qa_answer')->insert($insert_data);
                }
            } else {
                $id = app('model_qa_question')->insertGetId($data);
                if (!empty($insert_data)) {
                    array_walk($insert_data, function (&$value) use ($id) {
                        $value['question_id'] = $id;
                    });
                    app('model_qa_answer')->insert($insert_data);
                }
            }

            app('redis')->del('all:question');

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }

        return Response::sendData('success');
    }

    /**
     * @api {get} question 题目详情
     * @apiVersion 0.1.0
     * @apiName 题目详情
     * @apiGroup 题库
     * @apiParam {int} id
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "id": 1,
     * "title": "在爱情里你属于？",
     * "sort": 1,
     * "add_time": 1612322566,
     * "status": 1,
     * "qa_answer": [
     * {
     * "id": 1,
     * "title": "A.不争不抢，随缘",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 2,
     * "title": "B.主动出击",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 3,
     * "title": "C.欲拒还迎",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * },
     * {
     * "id": 4,
     * "title": "D.遍地撒网",
     * "question_id": 1,
     * "add_time": 1612322566,
     * "sort": 0
     * }
     * ]
     * }
     * }
     */
    public function show(Request $request)
    {
        $id = $request->input('id');
        $detail = app('model_qa_question')->with([
            'qa_answer' => function ($query) {
                $query->orderBy('sort', 'asc')->orderBy('id', 'asc');
            },
        ])->where('id', $id)->first();

        return Response::sendData($detail);
    }

    /**
     * @api {delete} question 删除题目
     * @apiVersion 0.1.0
     * @apiName 删除题目
     * @apiGroup 题库
     * @apiParam {numeric} id 必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            throw new BasicException(0, '请选择题目');
        }
        $detail = app('model_qa_question')->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '题目不存在');
        }
        app('model_qa_question')->where('id', $id)->delete();
        app('model_qa_answer')->where('question_id', $id)->delete();

        app('redis')->del('all:question');

        return Response::sendData('success');
    }
}
